<template>
  <div class="login-page min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4">
    <div class="max-w-md w-full">
      <!-- Logo -->
      <div class="text-center mb-8">
        <NuxtLink to="/" class="inline-flex items-center space-x-2">
          <div class="i-mdi-code-braces text-5xl text-primary-600" />
          <span class="text-3xl font-bold">代码小库</span>
        </NuxtLink>
        <p class="mt-2 text-gray-600">登录您的账户</p>
      </div>

      <!-- 登录表单 -->
      <div class="card">
        <form @submit.prevent="handleLogin">
          <!-- 邮箱 -->
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">
              邮箱
            </label>
            <input
              v-model="form.email"
              type="email"
              placeholder="请输入邮箱"
              class="input w-full"
              :class="{ 'border-red-500': errors.email }"
              @blur="validateEmail"
            />
            <p v-if="errors.email" class="text-red-500 text-sm mt-1">
              {{ errors.email }}
            </p>
          </div>

          <!-- 密码 -->
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">
              密码
            </label>
            <div class="relative">
              <input
                v-model="form.password"
                :type="showPassword ? 'text' : 'password'"
                placeholder="请输入密码"
                class="input w-full pr-10"
                :class="{ 'border-red-500': errors.password }"
                @blur="validatePassword"
              />
              <button
                type="button"
                class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500"
                @click="showPassword = !showPassword"
              >
                <div :class="showPassword ? 'i-mdi-eye-off' : 'i-mdi-eye'" />
              </button>
            </div>
            <p v-if="errors.password" class="text-red-500 text-sm mt-1">
              {{ errors.password }}
            </p>
          </div>

          <!-- 记住我 / 忘记密码 -->
          <div class="flex items-center justify-between mb-6">
            <label class="flex items-center">
              <input
                v-model="form.remember"
                type="checkbox"
                class="mr-2"
              />
              <span class="text-sm text-gray-600">记住我</span>
            </label>
            <NuxtLink
              to="/auth/forgot-password"
              class="text-sm text-primary-600 hover:text-primary-700"
            >
              忘记密码？
            </NuxtLink>
          </div>

          <!-- 登录按钮 -->
          <button
            type="submit"
            :disabled="loading"
            class="btn-primary w-full py-3 text-lg"
          >
            {{ loading ? '登录中...' : '登录' }}
          </button>

          <!-- 第三方登录 -->
          <div class="mt-6">
            <div class="relative">
              <div class="absolute inset-0 flex items-center">
                <div class="w-full border-t border-gray-300" />
              </div>
              <div class="relative flex justify-center text-sm">
                <span class="px-2 bg-white text-gray-500">或使用第三方登录</span>
              </div>
            </div>

            <div class="mt-6 grid grid-cols-3 gap-3">
              <button
                type="button"
                class="btn-outline py-3"
                @click="loginWithGithub"
              >
                <div class="i-mdi-github text-xl" />
              </button>
              <button
                type="button"
                class="btn-outline py-3"
                @click="loginWithWechat"
              >
                <div class="i-mdi-wechat text-xl text-green-600" />
              </button>
              <button
                type="button"
                class="btn-outline py-3"
                @click="loginWithQQ"
              >
                <div class="i-mdi-qqchat text-xl text-blue-600" />
              </button>
            </div>
          </div>
        </form>
      </div>

      <!-- 注册链接 -->
      <p class="mt-4 text-center text-sm text-gray-600">
        还没有账户？
        <NuxtLink to="/auth/register" class="text-primary-600 hover:text-primary-700 font-medium">
          立即注册
        </NuxtLink>
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { emailRule, passwordRule, requiredRule } from '~/utils/validation'

definePageMeta({
  layout: 'blank',
  middleware: 'guest',
})

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const form = reactive({
  email: '',
  password: '',
  remember: false,
})

const errors = reactive({
  email: '',
  password: '',
})

const showPassword = ref(false)
const loading = ref(false)

function validateEmail() {
  const result = requiredRule(form.email)
  if (result !== true) {
    errors.email = result
    return false
  }
  const emailResult = emailRule(form.email)
  if (emailResult !== true) {
    errors.email = emailResult
    return false
  }
  errors.email = ''
  return true
}

function validatePassword() {
  const result = requiredRule(form.password)
  if (result !== true) {
    errors.password = result
    return false
  }
  const passwordResult = passwordRule(form.password)
  if (passwordResult !== true) {
    errors.password = passwordResult
    return false
  }
  errors.password = ''
  return true
}

async function handleLogin() {
  // 验证表单
  const emailValid = validateEmail()
  const passwordValid = validatePassword()
  
  if (!emailValid || !passwordValid) {
    return
  }

  loading.value = true

  try {
    const result = await authStore.login(form)
    
    if (result.success) {
      // 跳转到原来的页面或首页
      const redirect = route.query.redirect as string || '/'
      router.push(redirect)
    } else {
      alert(result.message || '登录失败，请检查邮箱和密码')
    }
  } finally {
    loading.value = false
  }
}

function loginWithGithub() {
  // TODO: GitHub OAuth 登录
  console.log('GitHub 登录')
}

function loginWithWechat() {
  // TODO: 微信登录
  console.log('微信登录')
}

function loginWithQQ() {
  // TODO: QQ 登录
  console.log('QQ 登录')
}

// SEO
useSeoMeta({
  title: '登录 - 代码小库',
  robots: 'noindex',
})
</script>